import { JSONSchemaType } from "ajv";
import { IMiddleware } from "koa-router";

import { User } from "../model";
import { UserStatus } from "../model/user";
import {
  validateBody,
  validateQuery,
  validatePage
} from "../middleware/validate";
import { ajv } from "../util/ajv";
import { makeResponse, HttpStatusCode } from "../util/response";
import { objectIdValidator } from "./base";

interface GetUsers {
  current: number;
  limit: number;
  name?: string;
  status?: number;
  sort?: string;
}

interface CreateUser {
  name: string;
  username: string;
  password: string;
  email: string;
}

interface UpdateUser {
  name: string;
}

interface DeleteUsers {
  ids: string[];
}

const getUsersSchema: JSONSchemaType<GetUsers> = {
  type: "object",
  properties: {
    current: {
      type: "number"
    },
    limit: {
      type: "number"
    },
    name: {
      type: "string",
      nullable: true,
      isNotEmpty: true
    },
    status: {
      type: "integer",
      nullable: true,
      enum: Object.values(UserStatus) as number[]
    },
    sort: {
      type: "string",
      nullable: true,
      enum: ["1", "-1"]
    }
  },
  required: ["current", "limit"]
};
ajv.addSchema(getUsersSchema, "getUsers");

const createUserSchema: JSONSchemaType<CreateUser> = {
  type: "object",
  properties: {
    name: {
      type: "string",
      isNotEmpty: true
    },
    username: {
      type: "string",
      isNotEmpty: true
    },
    password: {
      type: "string",
      isNotEmpty: true
    },
    email: {
      type: "string",
      isNotEmpty: true,
      format: "email",
      errorMessage: {
        format: "email 格式不正确"
      }
    }
  },
  required: ["name", "username", "password", "email"]
};
ajv.addSchema(createUserSchema, "createUser");

const updateUserSchema: JSONSchemaType<UpdateUser> = {
  type: "object",
  properties: {
    name: { type: "string", isNotEmpty: true }
  },
  required: ["name"]
};
ajv.addSchema(updateUserSchema, "updateUser");

const deleteUsersSchema: JSONSchemaType<DeleteUsers> = {
  type: "object",
  properties: {
    ids: {
      type: "array",
      uniqueItems: true,
      items: { type: "string", isValidObjectId: true }
    }
  },
  required: ["ids"]
};
ajv.addSchema(deleteUsersSchema, "deleteUsers");

// user ObjectId 校验
export const userIdValidator: IMiddleware[] = [...objectIdValidator(User)];

// 获取所有用户
export const getUsersValidator: IMiddleware[] = [
  validateQuery("getUsers"),
  validatePage(User)
];

// 新增用户
export const createUserValidator: IMiddleware[] = [
  validateBody("createUser"),
  async (ctx, next) => {
    const { username } = ctx.request.body;
    const user = await User.findOne({ username });
    if (user) makeResponse(ctx, HttpStatusCode.BadRequest, "用户名已存在");
    else await next();
  }
];

// 更新用户
export const updateUserValidator: IMiddleware[] = [validateBody("updateUser")];

// 删除用户
export const deleteUsersValidator: IMiddleware[] = [
  validateQuery("deleteUsers")
];
